import axios from "axios"
import querystring from "querystring"

//请求拦截
axios.interceptors.request.use(config => {
    if (config.url!=="/api/login"&&config.url!=="/api/register") {
        config.headers.authorization = JSON.parse(sessionStorage.getItem("info")).token
    } 
    return config
})

//响应拦截
axios.interceptors.response.use(res => {
    console.log("本次请求地址：" + res.config.url);
    console.log(res);

    //失败统一处理
    if(res.data.code!==200){
        alert(res.data.msg)
    }

    return res;
})

export const get = (url, params = {}) => {
    return axios({
        url,
        params
    })
}

export const post = (url, params = {}, isFile = false) => {
    let data = null;
    if (isFile) {
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = querystring.stringify(params)
    }

    return axios({
        url,
        data,
        method: "post"
    })
}